from django.db.models import Sum

from goods_info.models import GoodsInventoryModel


def get_inventory_by_goods(goods_id, warehouse_id=0):
    """
        获取某个货品的当前库存，如果warehouse=0就是没有传，就查所有仓库的总库存
    """
    sum_inventory = 0

    if warehouse_id == 0:   # 就是查当前所有仓库的总库存
        # aggregate()是专门做聚合函数调用的。
        # Sum()就是聚合函数。
        result = GoodsInventoryModel.objects.filter(goods_id=goods_id).aggregate(cur_sum=Sum('cur_inventory'))
    else:
        result = GoodsInventoryModel.objects.filter(goods_id=goods_id, warehouse_id=warehouse_id).aggregate(cur_sum=Sum('cur_inventory'))

    if result['cur_sum'] and result['cur_sum'] != 'None':
        sum_inventory = result['cur_sum']
    return sum_inventory
